package cn.tqfeiyang.smartadmin.business.organization.service;

import cn.tqfeiyang.smartadmin.business.organization.mapper.EmployeeMapper;
import cn.tqfeiyang.smartadmin.business.organization.entity.EmployeeEntity;

import cn.tqfeiyang.smartadmin.commons.mybatis.IEntityCache;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import jakarta.annotation.Resource;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 员工缓存服务
 *
 * @author tqfeiyang
 * @since 2024-10-18
 */
@Service
@Slf4j
public class EmployeeCacheService implements IEntityCache<EmployeeEntity> {

    /**
     * 员工列表缓存
     */
    private static final String EMPLOYEE_LIST_CACHE = "business:organization:employee:list";

    /**
     * 员工map缓存
     */
    private static final String EMPLOYEE_MAP_CACHE = "business:organization:employee:map";

    /**
     * 员工映射接口
     */
    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 清空员工缓存
     */
    @CacheEvict(value = {
            EMPLOYEE_LIST_CACHE,
            EMPLOYEE_MAP_CACHE}, allEntries = true)
    @Override
    public void clearCache() {
        log.info("清空员工缓存");
    }

    /**
     * 查询员工列表
     *
     * @return 员工列表
     */
    @Cacheable(EMPLOYEE_LIST_CACHE)
    public List<EmployeeEntity> getEmployeeList() {
        return employeeMapper.selectList(Wrappers.emptyWrapper());
    }

    /**
     * 查询员工map
     *
     * @return 员工map
     */
    @Cacheable(EMPLOYEE_MAP_CACHE)
    public Map<Long, EmployeeEntity> getEmployeeMap() {
        return getEmployeeList().stream()
                .collect(Collectors.toMap(EmployeeEntity::getEmployeeId, Function.identity()));
    }

    /**
     * 根据员工id查询员工信息
     *
     * @param employeeId 员工id
     * @return 员工信息，如果不存在则返回null
     */
    public EmployeeEntity findEmployeeByEmployeeId(Long employeeId) {
        Assert.notNull(employeeId, "employeeId不能为空");
        return getEmployeeMap().get(employeeId);
    }
}
